#include "CForceRegister.h"
using namespace Core;

IForceRegister * getForceRegister()
{
	return CForceRegister::getForceRegisterInstance(); 
}

CForceRegister * CForceRegister::forceRegisterInstance=0;



CForceRegister * CForceRegister::getForceRegisterInstance()
{
	if(0==forceRegisterInstance)
	{
		forceRegisterInstance=new CForceRegister();
	}
	return forceRegisterInstance;
}
void CForceRegister::destroy()
{
  if (forceRegisterInstance)
  {
    delete forceRegisterInstance;
  }
}

CForceRegister::CForceRegister()
{
}

void CForceRegister::add(IEntity * entity, int forceGeneratorId)
{
	ForceRegistration newPair;
	newPair.entity=(CEntity*)entity;
	newPair.forceGeneratorId=forceGeneratorId;
	registrations.push_back(newPair);
}

void CForceRegister::remove(IEntity * entity, int forceGeneratorId)
{
	for(Registry::iterator it=registrations.begin();it!=registrations.end();++it)
	{
		if((*it).entity==entity && (*it).forceGeneratorId==forceGeneratorId)
		{
			registrations.erase(it);
			break;
		}
	}
}


void CForceRegister::clear()
{
	registrations.clear();
  for (int i = 0; i< forceGenerators.size();++i)
  {
    delete forceGenerators[i];
  }
}

void CForceRegister::update(real dT)
{
	for(Registry::iterator it=registrations.begin();it!=registrations.end();++it)
	{
		forceGenerators[it->forceGeneratorId]->update(it->entity,dT);
	}
	for(Registry::iterator it=registrations.begin();it!=registrations.end();++it)
	{
		it->entity->integrate(dT);
	}
}

int CForceRegister::addForceGenerator(IForceGenerator * forceGenerator)
{
	forceGenerators.push_back(forceGenerator);
	return forceGenerators.size()-1;
}